<script setup lang="ts">
import {
  createOrderIdAPI,
  getPatientInfoAPI,
  getPreConsultOrderAPI
} from '@/apis/consult'
import type { ConsultOrderPreData, PartialConsult } from '@/types/consult'
import { onMounted, ref } from 'vue'
import { useConsultStore } from '@/stores'
import type { PatientItem } from '@/types/user'
import { showConfirmDialog, showDialog, showToast } from 'vant'
import { onBeforeRouteLeave } from 'vue-router'
import router from '@/router'
const store = useConsultStore()
// 定义响应式数据 保存预支付
const preOrderInfo = ref<ConsultOrderPreData>()
// 响应式数据 保存患者的信息
const patientInfo = ref<PatientItem>()
// 定义函数 获取预支付的数据
const getPreOrderInfo = async () => {
  const res = await getPreConsultOrderAPI({
    type: store.consult.type,
    illnessType: store.consult.illnessType
  })
  // console.log(res)
  preOrderInfo.value = res.data
  store.setCouponId(preOrderInfo.value.couponId)
}

// 定义函数 获取患者的数据
const getPatientInfo = async () => {
  if (!store.consult.patientId) return
  const res = await getPatientInfoAPI(store.consult.patientId)
  // console.log(res)
  patientInfo.value = res.data
}
type Key = keyof PartialConsult
onMounted(() => {
  // 定义一个数组数组里面保存 填写的记录的字段名
  const validArr: Key[] = [
    'type',
    'consultFlag',
    'illnessDesc',
    'illnessTime',
    'depId',
    'patientId',
    'illnessType'
  ]
  const isValue = validArr.every((item) => store.consult[item] !== undefined)
  if (!isValue) {
    return showDialog({
      title: '温馨提示',
      message:
        '问诊信息不完整请重新填写，如有未支付的问诊订单可在问诊记录中继续支付',
      closeOnPopstate: false
    }).then(() => {
      // 跳转到首页
      router.push('/')
    })
  }
  getPreOrderInfo()
  getPatientInfo()
})
// 同意选项
const isArgee = ref(false)
// 控制抽屉组件的显示与隐藏
const show = ref(false)
// // 保存支付平台
// const paymentMethod = ref<0 | 1>()
const loading = ref(false)
// 保存订单id
const orderId = ref<string>('')
const onSumit = async () => {
  // 判断是否勾选了我同意支付
  if (!isArgee.value) return showToast('请勾选同意支付')
  // 开启loading 效果
  loading.value = true
  // 发送请求生成订单
  const res = await createOrderIdAPI(store.consult)
  // console.log(res)
  // 保存订单id
  orderId.value = res.data.id
  // 关闭loading 效果
  loading.value = false
  // 清空数据
  store.clear()
  // 显示抽屉组件
  show.value = true
}

// 阻止点击返回
onBeforeRouteLeave(() => {
  // 如果有 订单id 阻止其返回
  if (orderId.value) {
    return false
  }
})

// 关闭前的回调函数，返回 false 可阻止关闭，支持返回 Promise
const onClose = () => {
  return showConfirmDialog({
    title: '温馨提示',
    message: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
    confirmButtonText: '继续支付',
    cancelButtonText: '仍要关闭'
  })
    .then(() => {
      return false
    })
    .catch(() => {
      orderId.value = ''
      // 让其跳转到问诊记录
      router.push('/user/consult')
      // 关闭动作面板
      return true
    })
}

// // 开始支付
// const onPay = async () => {
//   // 判断是否选择了 支付平台
//   if (paymentMethod.value === undefined) return showToast('请选择支付平台')
//   // 提示支付中
//   showLoadingToast({
//     message: '正在支付',
//     duration: 0
//   })
//   // 向服务器发送请求
//   const res = await getConsultPayAPI({
//     paymentMethod: paymentMethod.value,
//     orderId: orderId.value,
//     payCallback: 'http://localhost:8080/room'
//   })
//   // console.log(res.data.payUrl)
//   location.href = res.data.payUrl
// }
</script>

<template>
  <div class="consult-pay-page" v-if="preOrderInfo && patientInfo">
    <cp-nav-bar title="支付" />
    <div class="pay-info">
      <p class="tit">图文问诊 {{ preOrderInfo.payment }} 元</p>
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <p class="desc">
        <span>极速问诊</span>
        <span>自动分配医生</span>
      </p>
    </div>
    <van-cell-group>
      <van-cell title="优惠券" :value="`-¥${preOrderInfo.couponDeduction}`" />
      <van-cell title="积分抵扣" :value="`-¥${preOrderInfo.pointDeduction}`" />
      <van-cell
        title="实付款"
        :value="`¥${preOrderInfo.actualPayment}`"
        class="pay-price"
      />
    </van-cell-group>
    <div class="pay-space"></div>
    <van-cell-group>
      <van-cell
        title="患者信息"
        :value="`${patientInfo?.name} | ${patientInfo.genderValue} | ${patientInfo.age}岁`"
      ></van-cell>
      <van-cell title="病情描述" :label="store.consult.illnessDesc"></van-cell>
    </van-cell-group>
    <div class="pay-schema">
      <van-checkbox v-model="isArgee">
        我已同意
        <span class="text">支付协议</span></van-checkbox
      >
    </div>
    <van-submit-bar
      :loading="loading"
      button-type="primary"
      :price="preOrderInfo.actualPayment * 100"
      button-text="立即支付"
      text-align="left"
      @click="onSumit"
    />
    <!-- close-on-click-overlay 是否在点击遮罩层后关闭 默认关闭 -->
    <cp-pay-sheet
      v-model:show="show"
      :order-id="orderId"
      :onClose="onClose"
      :actualPayment="preOrderInfo.actualPayment"
      pay-callback="/room"
    ></cp-pay-sheet>
  </div>
  <!-- 骨架屏 -->
  <div class="consult-pay-page" v-else>
    <cp-nav-bar title="支付" />
    <van-skeleton title :row="15" style="margin-top: 20px" />
  </div>
</template>

<style lang="scss" scoped>
.consult-pay-page {
  padding: 46px 0 50px 0;
}
.pay-info {
  display: flex;
  padding: 15px;
  flex-wrap: wrap;
  align-items: center;
  .tit {
    width: 100%;
    font-size: 16px;
    margin-bottom: 10px;
  }
  .img {
    margin-right: 10px;
    width: 38px;
    height: 38px;
    border-radius: 4px;
    overflow: hidden;
  }
  .desc {
    flex: 1;
    > span {
      display: block;
      color: var(--cp-tag);
      &:first-child {
        font-size: 16px;
        color: var(--cp-text2);
      }
    }
  }
}
.pay-price {
  ::v-deep() {
    .vam-cell__title {
      font-size: 16px;
    }
    .van-cell__value {
      font-size: 16px;
      color: var(--cp-price);
    }
  }
}
.pay-space {
  height: 12px;
  background-color: var(--cp-bg);
}
.pay-schema {
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  .text {
    color: var(--cp-primary);
  }
}
::v-deep() {
  .van-submit-bar__button {
    font-weight: normal;
    width: 160px;
  }
}
.pay-type {
  .amount {
    padding: 20px;
    text-align: center;
    font-size: 16px;
    font-weight: bold;
  }
  .btn {
    padding: 15px;
  }
  .van-cell {
    align-items: center;
    .cp-icon {
      margin-right: 10px;
      font-size: 18px;
    }
    .van-checkbox :deep(.van-checkbox__icon) {
      font-size: 16px;
    }
  }
}
</style>
